<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      :model="queryParams"
      ref="queryForm"
      size="small"
      inline
      label-width="68px"
    >
      <el-form-item label="用户账号" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户账号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phonenumber">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="用户状态"
          filterable
          clearable
        >
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">
          搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['mc:user:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['mc:user:remove']"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >
          批量删除
        </el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table
      v-loading="loading"
      :data="dataList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="序号" type="index" width="80" align="center" />
      <el-table-column label="用户昵称" align="center" prop="nickName" />
      <el-table-column label="性别" align="center" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex" />
        </template>
      </el-table-column>
      <el-table-column label="用户账号" align="center" prop="userName" />
      <el-table-column label="手机号码" align="center" prop="phonenumber" width="120" />
      <el-table-column label="所属机构" align="center" prop="institutionName" />
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="160">
        <template slot-scope="scope" v-if="scope.row.userId !== 1">
          <el-button
            v-hasPermi="['mc:user:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >
            修改
          </el-button>
          <el-button
            v-hasPermi="['mc:user:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
          <el-dropdown
            size="mini"
            @command="(command) => handleCommand(command, scope.row)"
            v-hasPermi="['mc:user:resetPwd']"
          >
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right"
              >更多</el-button
            >
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-hasPermi="['mc:user:resetPwd']"
                command="handleResetPwd"
                icon="el-icon-key"
              >
                重置密码
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户配置对话框 -->
    <User-form
      v-model="open"
      :form="editForm"
      :title="editForm.userId ? '修改员工' : '添加员工'"
      :sex-list="dict.type.sys_user_sex"
      :status-list="dict.type.sys_normal_disable"
      @submit="submitForm"
    />
  </div>
</template>

<script>
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  resetUserPwd,
  changeUserStatus,
} from "@/api/mc/user";
import UserForm from "./components/UserForm.vue";

export default {
  name: "User",
  dicts: ["sys_normal_disable", "sys_user_sex"],
  components: { UserForm },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      dataList: null,
      // 是否显示弹出层
      open: false,
      // 默认密码
      initPassword: null,
      // 表单参数
      editForm: {
        userId: null,
        userName: null,
        nickName: null,
        password: null,
        phonenumber: null,
        institutionId: null,
        email: null,
        sex: null,
        status: "0",
        remark: null,
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: 2,
        userName: null,
        phonenumber: null,
        status: null,
      },
    };
  },
  created() {
    this.getList();
    this.getConfigKey("sys.user.initPassword").then((res) => {
      this.initPassword = res.msg;
    });
  },
  watch: {
    open(val) {
      if (!val) {
        this.editForm = {
          userId: null,
          userName: null,
          nickName: null,
          password: null,
          phonenumber: null,
          institutionId: null,
          email: null,
          sex: null,
          status: "0",
          remark: null,
        };
      }
    },
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams)
        .then((res) => {
          this.dataList = res.rows;
          this.total = res.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal
        .confirm(`确认要${text}【${row.userName}】用户吗？`)
        .then(() => {
          changeUserStatus(row.userId, row.status).then(() => {
            this.$modal.msgSuccess(text + "成功");
          });
        })
        .catch(() => {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        default:
          break;
      }
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt(`请输入【${row.userName}】的新密码`, "重置密码", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
      })
        .then(({ value }) => {
          resetUserPwd(row.userId, value).then((res) => {
            this.$modal.msgSuccess("修改成功，新密码是：" + value);
          });
        })
        .catch(() => {});
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.editForm.password = this.initPassword;
      this.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      getUser(row.userId).then((res) => {
        this.editForm = res.data;
        this.editForm.password = "";
        this.open = true;
      });
    },
    /** 提交按钮 */
    submitForm(form) {
      let request = form.userId ? updateUser : addUser;
      request(form).then((res) => {
        this.$modal.msgSuccess("操作成功");
        this.open = false;
        this.getList();
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$modal
        .confirm(`确认删除已选中的${row.userId ? 1 : this.ids.length}条用户数据吗？`)
        .then(() => {
          delUser(userIds).then(() => {
            this.getList();
            this.$modal.msgSuccess("删除成功");
          });
        })
        .catch(() => {});
    },
  },
};
</script>
